package com.handinhand.mobile;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.handinhand.mobile.conn.HandInHandCallback;
import com.handinhand.mobile.model.User;
import com.handinhand.mobile.service.UserService;
/**
 * It is the main activity of the application. If user is not logged it provides an interface 
 * to go signup and about us activities.If user is logged HomeActivity is started onCreate.
 * @author ekremsekerci
 *
 */
public class MainActivity extends BaseActivity {

	private Button loginButton;
	private Button signUpNavButton;
	private EditText loginUsername;
	private EditText loginPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		HandInHandApplication application = (HandInHandApplication) getApplication();
		if (application.getLoggedUser() != null) {
			Intent intent = new Intent(MainActivity.this, HomeActivity.class);
			startActivity(intent);
			finish();
		}

		setContentView(R.layout.login);

		setupUI();
	}
	/**
	 * setup UI of this activity.
	 */
	private void setupUI() {
		loginButton = (Button) findViewById(R.id.btnLogin);
		loginButton.setOnClickListener(onLoginButtonClick);

		loginUsername = (EditText) findViewById(R.id.etUsername);
		loginPassword = (EditText) findViewById(R.id.etPassword);

		signUpNavButton = (Button) findViewById(R.id.btnSignUpNav);
		signUpNavButton.setOnClickListener(onSignUpNavButtonClick);
	}

	private OnClickListener onLoginButtonClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String username = loginUsername.getText().toString();
			String password = loginPassword.getText().toString();

			if (username.trim().equals("") || password.trim().equals("")) {
				Toast.makeText(MainActivity.this, "Username and/or password cannot be empty!", Toast.LENGTH_SHORT).show();
				return;
			}

			UserService userService = new UserService(getApp());
			userService.login(username, password, new HandInHandCallback<User>() {
				public void onSuccess(User response) {
					setLoggedUser(response);
					// This is where user successfully signed in and directed to his/her home screen.
					Intent intent = new Intent(MainActivity.this, HomeActivity.class);
					startActivity(intent);
					finish();
				}

				public void onFail(String errorMessage) {
					Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show();					
				}
			});
		}
	};

	private OnClickListener onSignUpNavButtonClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MainActivity.this, SignUpActivity.class);
			startActivity(intent);
			finish();
		}
	};
}
